﻿using AutoMapper;
using MediatR;
using RBAC.Domain;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.Role;
using System.Data.SqlTypes;
using System.Transactions;

namespace RBAC.Write.Api.Application.Handler.Role
{
    public class CreateRoleHandler : IRequestHandler<CreateRoleCommand, APIResult<int>>
    {
        private readonly IBaseRepository<RoleModel> roleRepository;
        private readonly IBaseRepository<RolePermissionModel> rolepermissionRepository;
        private readonly IMapper mapper;
        private readonly ILogger<CreateRoleHandler> logger;

        public CreateRoleHandler(IBaseRepository<RoleModel> roleRepository, IBaseRepository<RolePermissionModel> rolepermissionRepository, IMapper mapper, ILogger<CreateRoleHandler> logger)
        {
            this.roleRepository = roleRepository;
            this.rolepermissionRepository = rolepermissionRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 创建角色
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(CreateRoleCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            var role =mapper.Map<RoleModel>(request);
            using (TransactionScope tran = new TransactionScope())
            {
                try
                {
                    var r = roleRepository.Create(role);
                    foreach (var item in request.PermissionIds)
                    {
                        var permission = new RolePermissionModel()
                        {
                            RoleId = role.Id,
                            PermissionId = item,
                        };
                        var r2 = rolepermissionRepository.Create(permission);

                    }
                    tran.Complete();
                    res.Code= APIEnums.Success;
                    res.Msg = "添加成功";
                    res.Data = r;
                    logger.LogInformation($"添加角色{request.RoleName}成功");
                  
                }
                catch (Exception)
                {
                    logger.LogError("添加角色失败");
                    res.Code = APIEnums.Error;
                    res.Msg = "添加角色失败";
                    res.Data = 0;

                    throw;
                }
            }
            return Task.FromResult(res);
            
            

        }
    }
}
